﻿using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp0713Demo.HistoryData.Dto;

namespace Abp0713Demo.HistoryData
{
    public class HistoryDataAppService:ApplicationService,IHistoryDataAppService
    {
        readonly IRepository<PointInfo> _pointRepository;
        readonly IRepository<HistoryDataTable, long> _historyDataRepository;
        private readonly HistoryManager _historyManager;

        public HistoryDataAppService(HistoryManager historyManager, IRepository<PointInfo> pointRepository, IRepository<HistoryDataTable, long> historyDataRepository)
        {
            _historyManager = historyManager;
            _pointRepository = pointRepository;
            _historyDataRepository = historyDataRepository;
        }

        public async Task InsertTestData()
        {
            await _historyManager.InsertTestData();
        }

        public async Task<long> TestDataCount()
        {
            return await _historyDataRepository.LongCountAsync();
        }

        public async Task<HistoryDataDto> GetHistory(int[] pointIds,long begin, long end)
        {
            var historyResult = new HistoryDataDto() { Begin = begin, End = end };
            if (pointIds == null) return historyResult;

            var historyData =await _historyDataRepository.GetAll()
                    .Where(x => pointIds.Contains(x.PointId) && x.Id >= begin && x.Id <= end)
                    .ToListAsync();

            //对点进行分组,数据按时间排序
            var pointHis = historyData.GroupBy(x => x.PointId).ToDictionary(g => g.Key, g => g.OrderBy(x=>x.Id).ToList());
            foreach (var pointHi in pointHis)
            {
                var itemBuffer = new HistoryDataItemBuffer {PointId = pointHi.Key};
                itemBuffer.Data = pointHi.Value.Select(x => new double[2] {x.Id, x.Value}).ToList();

                historyResult.ItemBuffers.Add(itemBuffer);
            }

            return historyResult;
        }

        public List<PointListDto> GetPoints()
        {
            var points = _pointRepository.GetAllList();
            return points.MapTo<List<PointListDto>>();
        }
    }
}